package com.example.teach.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.teach.entity.*;
import com.example.teach.entity.Clazz;
import com.example.teach.service.ClassService;
import com.example.teach.service.CourseService;
import com.example.teach.service.ScheduleService;
import com.example.teach.service.UserService;
import com.example.teach.vo.ScheduleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/schedule")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassService classService;

    @Autowired
    private UserService userService;

    @PutMapping("/update")
    public Result update(@RequestBody Schedule schedule) {
        scheduleService.updateById(schedule);
        return Result.success();
    }

    @PostMapping("/create")
    public Result create(@RequestBody Schedule schedule) {
        if(schedule.getStartWeek()<1 || schedule.getStartWeek()>18){
            return Result.error("开使周数为1-17");
        }
        if(schedule.getEndWeek()<2 || schedule.getEndWeek()>19){
            return Result.error("结束周数为2-18");
        }
        if(schedule.getDay() < 1 || schedule.getDay()>7){
            return Result.error("一周只有7天");
        }
        if(schedule.getStartTime() < 1 || schedule.getStartTime()>11){
            return Result.error("开始节次范围是1-11");
        }
        if(schedule.getEndTime() < 2 || schedule.getEndTime()>12){
            return Result.error("结束节次范围是2-12");
        }

//        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("class_id", schedule.getClassId());
//
//        if(scheduleService.exists(queryWrapper)){
//            // 先查询已存在的记录，获取id
//            Schedule existingSchedule = scheduleService.getOne(queryWrapper);
//            if(existingSchedule != null){
//                // 设置id到新的schedule对象中
//                schedule.setId(existingSchedule.getId());
//                // 然后再执行更新
//                scheduleService.updateById(schedule);
//            }
//            return Result.success();
//        }
        String res = scheduleService.create(schedule);
        if(res.equals("课程创建成功")) {
            return Result.success("课程创建成功");
        }
        return Result.error(res);
    }

    @GetMapping("/pageall")
    public Result pageAll(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize",defaultValue = "10") Integer PageSize,
                          @RequestParam(value = "courseName",defaultValue = "") String courseName,
                          @RequestParam(value = "className",defaultValue = "") String className,
                          @RequestParam(value = "teacherName",defaultValue = "") String teacherName
                          ){
        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(courseName)) {
            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.like("course_name", courseName);
            List<Course> courses = courseService.list(courseQueryWrapper);
            if (courses != null && !courses.isEmpty()) {
                List<Integer> courseIds = courses.stream().map(Course::getId).toList();
                queryWrapper.in("course_id", courseIds);
            }
        }
        if(StrUtil.isNotBlank(className)){
            QueryWrapper<Clazz> classQueryWrapper = new QueryWrapper<>();
            classQueryWrapper.like("class_name",className);
            List<Clazz> clazzes = classService.list(classQueryWrapper);
            if(clazzes != null && !clazzes.isEmpty()){
                List<Integer> classIds = clazzes.stream().map(Clazz::getId).toList();
                queryWrapper.in("class_id",classIds);
            }
        }
        if(StrUtil.isNotBlank(teacherName)){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like("user_name",teacherName);
            List<User> users = userService.list(userQueryWrapper);
            if(users != null && !users.isEmpty()){
                List<Integer> userIds = users.stream().map(User::getUserId).toList();
                queryWrapper.in("teacher_id",userIds);
            }
        }

        Page<Schedule> pages = scheduleService.page(new Page<>(pageNum, PageSize), queryWrapper);

        List<ScheduleVO> scheduleVOList = new ArrayList<>();
        for (Schedule schedule : pages.getRecords()) {
            ScheduleVO scheduleVO = new ScheduleVO();
            scheduleVO.setId(schedule.getId());
            scheduleVO.setCourseId(schedule.getCourseId());
            scheduleVO.setClassId(schedule.getClassId());
            scheduleVO.setTeacherId(schedule.getTeacherId());
            scheduleVO.setStartWeek(schedule.getStartWeek());
            scheduleVO.setEndWeek(schedule.getEndWeek());
            scheduleVO.setDay(schedule.getDay());
            scheduleVO.setStartTime(schedule.getStartTime());
            scheduleVO.setEndTime(schedule.getEndTime());
            scheduleVO.setClassroom(schedule.getClassroom());

            if (schedule.getCourseId() != null) {
                Course course = courseService.getById(schedule.getCourseId());
                if (course != null) {
                    scheduleVO.setCourseName(course.getCourseName());
                }
            }

            if (schedule.getClassId() != null) {
                Clazz clazz = classService.getById(schedule.getClassId());
                if (clazz != null) {
                    scheduleVO.setClassName(clazz.getClassName());
                    Integer teacherId = clazz.getTeacherId();
                    scheduleVO.setTeacherId(teacherId);
                    User teacher = userService.getByteacherId(teacherId);
                    if (teacher != null) {
                        scheduleVO.setTeacherName(teacher.getUserName());
                    }
                }
            }

            scheduleVOList.add(scheduleVO);
        }

        Page<ScheduleVO> resultPage = new Page<>();
        resultPage.setRecords(scheduleVOList);
        resultPage.setTotal(pages.getTotal());
        resultPage.setSize(pages.getSize());
        resultPage.setCurrent(pages.getCurrent());
        resultPage.setPages(pages.getPages());

        return Result.success(resultPage);
    }

}
